package com.hushow.bus.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hushow.bus.demo.event.RouteRemoteApplicationEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.bus.event.AckRemoteApplicationEvent;
import org.springframework.cloud.bus.event.SentApplicationEvent;
import org.springframework.cloud.bus.event.TraceListener;
import org.springframework.cloud.bus.jackson.RemoteApplicationEventScan;
import org.springframework.context.event.EventListener;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@SpringBootApplication(scanBasePackages = {"com.hushow.bus.demo.**"})
@RemoteApplicationEventScan(basePackageClasses = {RouteRemoteApplicationEvent.class})
public class SubscribeDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SubscribeDemoApplication.class, args);
	}


	@EventListener
	public void onUserRemoteApplicationEvent(RouteRemoteApplicationEvent event) {

		log.info("UserRemoteApplicationEvent:{}, Source:{}, destinationService: {}",event.getSource(),
				event.getOriginService(),
				event.getDestinationService());

		log.info("user: {}", JSONObject.toJSONString(event.getSource()));
	}


	@EventListener
	public void onAck(AckRemoteApplicationEvent event) {
		this.getReceivedTrace(event);
	}

	@EventListener
	public void onSend(SentApplicationEvent event) {
		this.getSentTrace(event);
	}


	protected Map<String, Object> getSentTrace(SentApplicationEvent event) {
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		map.put("signal", "spring.cloud.bus.sent");
		map.put("type", event.getType().getSimpleName());
		map.put("id", event.getId());
		map.put("origin", event.getOriginService());
		map.put("destination", event.getDestinationService());
		log.debug(JSON.toJSONString(map));
		return map;
	}

	protected Map<String, Object> getReceivedTrace(AckRemoteApplicationEvent event) {
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		map.put("signal", "spring.cloud.bus.ack");
		map.put("event", event.getEvent().getSimpleName());
		map.put("id", event.getAckId());
		map.put("origin", event.getOriginService());
		map.put("destination", event.getAckDestinationService());
		log.debug(JSON.toJSONString(map));
		return map;
	}
}
